package wb.is.besti.edu.cd.emergency_responsesys.pages;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;

import java.util.ArrayList;
import java.util.List;

import wb.is.besti.edu.cd.emergency_responsesys.HomeActivity;
import wb.is.besti.edu.cd.emergency_responsesys.R;
import wb.is.besti.edu.cd.emergency_responsesys.utils.GetLocation;
import wb.is.besti.edu.cd.emergency_responsesys.utils.MyLocations;

public class MapPageFragment extends Fragment {

    private LocationClient mLocationClient;
    private TextView textView;
    private MapView mapView;
    private boolean isFirstLocate = true;
    private BaiduMap baiduMap;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        SDKInitializer.initialize(getActivity().getApplicationContext());
        View view = inflater.inflate(R.layout.mappage_second,container,false);
        mLocationClient = new LocationClient(this.getActivity().getApplicationContext());
        mLocationClient.registerLocationListener(new MyLocationListener());
        mapView = (MapView) view.findViewById(R.id.baidu_map);
        mapView.showScaleControl(false);
        mapView.showZoomControls(false);
        baiduMap = mapView.getMap();
        UiSettings uiSettings = baiduMap.getUiSettings();
        uiSettings.setOverlookingGesturesEnabled(true);
        uiSettings.setRotateGesturesEnabled(true);
        baiduMap.setMyLocationEnabled(true);
        baiduMap.setBuildingsEnabled(true);
        List<String> permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.READ_PHONE_STATE)!=PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.READ_PHONE_STATE);
        }
        if (ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (!permissionList.isEmpty()){
            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
            MapPageFragment.this.requestPermissions(permissions,1);
        }
        else {
            requestLocation();
        }
        return view;
    }
    private void requestLocation(){
        initLocation();
        mLocationClient.start();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
       switch (requestCode){
           case 1:
               if (grantResults.length>0){
                   for (int result:grantResults){
                       if (result != PackageManager.PERMISSION_GRANTED){
                           Toast.makeText(this.getActivity(),"同意所有权限",Toast.LENGTH_LONG).show();
                           this.getActivity().finish();
                           return;
                       }
                   }
                   requestLocation();
               }
               else {
                   Toast.makeText(this.getActivity(),"位置错误",Toast.LENGTH_SHORT).show();
                   this.getActivity().finish();
               }
               break;
               default:
       }
    }

    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);
        option.setScanSpan(5000);
        option.setIsNeedAddress(true);
        option.setCoorType("bd09ll");
        option.setOpenGps(true);
        option.setLocationNotify(true);
        option.setIsNeedLocationDescribe(true);
        mLocationClient.setLocOption(option);
    }

    private double m_latitude;
    private double m_longitude;
    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            m_latitude = bdLocation.getLatitude();
            m_longitude = bdLocation.getLongitude();
            StringBuilder currentPosition = new StringBuilder();
            currentPosition.append("国家:").append(bdLocation.getCountry()).append("\n");
            currentPosition.append("省:").append(bdLocation.getProvince()).append("\n");
            currentPosition.append("市:").append(bdLocation.getCity()).append("\n");
            currentPosition.append("区:").append(bdLocation.getDistrict()).append("\n");
            currentPosition.append("街道:").append(bdLocation.getStreet()).append("\n");
            currentPosition.append("位置:").append(bdLocation.getAddrStr()).append("\n");
            textView.setText(currentPosition);

            if (bdLocation.getLocType()==BDLocation.TypeCacheLocation||bdLocation.getLocType()==BDLocation.TypeNetWorkLocation){
                nagigateTo(bdLocation);
                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(bdLocation.getRadius())
                        .direction(100).latitude(m_latitude).longitude(m_longitude).build();
                baiduMap.setMyLocationData(locData);
            }
        }
    }

    public void nagigateTo(BDLocation location){
        LatLng latLng = null;
        if (isFirstLocate){
            latLng=new LatLng(location.getLatitude(),location.getLongitude());
            MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(latLng);
            baiduMap.animateMapStatus(update);
            update= MapStatusUpdateFactory.zoomTo(16f);
            baiduMap.animateMapStatus(update);
            isFirstLocate = false;
        }
        MyLocationData locationData = new MyLocationData.Builder().accuracy(location.getRadius()).direction(100)
                .latitude(location.getLatitude()).longitude(location.getLongitude()).build();
        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.mipmap.ic_action_anchor);
        OverlayOptions options = new MarkerOptions().position(latLng).icon(bitmapDescriptor);
        baiduMap.setMyLocationData(locationData);
        baiduMap.addOverlay(options);
        //重写

    }

    private void initMarker() throws Exception{
        List<MyLocations> locationsList = GetLocation.getLocationsList();
        LatLng latLng = null;
        OverlayOptions options = null;
        Marker marker = null;
        MyLocations myLocations = null;
        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.mipmap.ic_action_anchor);
        for (int i=0;i<locationsList.size();i++){
            myLocations = locationsList.get(i);
            latLng = new LatLng(myLocations.getLatitudu(),myLocations.getLongitude());
            options = new MarkerOptions().position(latLng).icon(bitmapDescriptor).zIndex(9).draggable(true);
            marker = (Marker)baiduMap.addOverlay(options);
            Bundle bundle = new Bundle();
            bundle.putSerializable("marker",locationsList.get(i));
            marker.setExtraInfo(bundle);
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
        mapView.onDestroy();
        baiduMap.setMyLocationEnabled(false);
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }
}

